import './index.css';
import {
  Layout,
  Input,
  Button,
  Form,
  message,
  Modal,
  Checkbox,
  Spin,
  Row,
  Col,
  Image,
  Card,
} from 'antd';
import userImg from './images/icon-user.png';
import passImg from './images/icon-pass.png';
import logoImg from './images/hebut.png';
import { history, useRequest } from 'umi';
import RcResizeObserver from 'rc-resize-observer';
import { useState } from 'react';

const LoginView = (props: any) => {
  const [backgroudShape, setBackgroudShape] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
  const [loginLoading, setLoginLoading] = useState(false);

  async function login(params: any) {
    setLoginLoading(true);
    const response = await fetch(
      `http://10.1.40.84:9993/login/submit?username=${
        params.username
      }&password=${encodeURIComponent(params.password)}`,
      {
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          Accept: 'application/json',
        },
        method: 'POST',
      },
    );

    return response.json();
  }

  const getUserInfo = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/user/getUserInfo',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        localStorage.setItem('personInfo', JSON.stringify(result.res));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );

  const onFinish = (values: any) => {
    console.log(values);
    login(values)
      .then((data) => {
        if (data.code === 200) {
          console.log(data);
          localStorage.setItem('isLogin', '1');
          localStorage.setItem('token', data?.data.token || '');
          localStorage.setItem('auth', JSON.stringify(data?.data?.auth || ''));
          localStorage.setItem('fulfil', data?.data?.flag + '');
          localStorage.setItem('account', data.data.name);

          for (let i = 0; i < data?.data?.auth?.length; i++) {
            if (data?.data?.auth[i].authority === 'ROLE_学生') {
              localStorage.setItem('identity', '学生');
              break;
            }
            if (data?.data?.auth[i].authority === 'ROLE_管理员') {
              localStorage.setItem('identity', '管理员');
              break;
            }
            localStorage.setItem('identity', '用户');
          }

          if (localStorage.getItem('identity') === '用户') {
            let typeNumber: any = 0;
            for (let i = 0; i < data?.data?.auth?.length; i++) {
              if (data?.data?.auth[i].authority === 'ROLE_子方向负责人') {
                typeNumber = typeNumber + 1;
              }
              if (data?.data?.auth[i].authority === 'ROLE_方向负责人') {
                typeNumber = typeNumber + 2;
              }
            }
            switch (typeNumber) {
              case 1:
                localStorage.setItem('identitySub', '子方向负责人');
                break;
              case 2:
                localStorage.setItem('identitySub', '方向负责人');
                break;
              case 3:
                localStorage.setItem('identitySub', '方向负责人+子方向负责人');
                break;
              default:
                break;
            }
          }

          getUserInfo.run().then(() => {
            if (localStorage.getItem('identity') === '学生') {
              history.push('/PostgraduateDevelop/PersonalManagement');
            } else {
              history.push('/PersonalCenter/BasicMsg');
            }
            setLoginLoading(false);
          });
        } else {
          message.error(data.msg);
          setLoginLoading(false);
        }
      })
      .catch((e) => {
        message.error('出现网络问题，请检查！！');
        setLoginLoading(false);
      });
  };

  return (
    // <RcResizeObserver
    //   key="resize-observer"
    //   onResize={(offset) => {
    //     // console.log(offset);
    //     setBackgroudShape({
    //       width: offset.width,
    //       height: offset.height,
    //     });
    //     // setResponsive(offset.width < 596);
    //   }}
    // >
    <Row>
      <Col
        span={24}
        className={'backgroundImage'}
        style={{ height: backgroudShape.height, width: backgroudShape.width }}
      >
        <div
          style={{
            color: '#219ebc',
            fontSize: 42,
            textAlign: 'center',
            marginTop: 50,
            // marginLeft: 100,
            fontFamily: 'cursive',
          }}
        >
          省部共建电工装备可靠性与智能化国家重点实验室
        </div>
        <div
          style={{
            color: '#219ebc',
            fontSize: 28,
            // marginLeft: 100,
            textAlign: 'center',
            fontFamily: 'cursive',
          }}
        >
          State Key Laboratory of Reliability and Intelligence of Electrical
          Equipment
        </div>
        <div>
          <div
            style={{
              marginTop: 100,
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <Card>
              <Form
                name="basic"
                initialValues={{ remember: true }}
                onFinish={onFinish}
                // onFinish={() => {
                //   history.push('/PostgraduateDevelop/PersonalManagement');
                // }}
                style={{
                  marginTop: 30,
                }}
              >
                <Form.Item
                  name="username"
                  rules={[
                    {
                      required: true,
                      message: 'Please input your username!',
                    },
                  ]}
                >
                  <Input
                    style={{ width: 280 }}
                    prefix={<img src={userImg} />}
                    className="login-input"
                  />
                </Form.Item>

                <Form.Item
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: 'Please input your password!',
                    },
                  ]}
                >
                  <Input.Password
                    prefix={<img src={passImg} />}
                    className="login-input"
                  />
                </Form.Item>
                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    style={{ width: 280 }}
                    loading={loginLoading}
                  >
                    <span>登&nbsp;&nbsp;&nbsp;&nbsp;录</span>
                  </Button>
                </Form.Item>
              </Form>
            </Card>
          </div>
        </div>
      </Col>
    </Row>
  );
};

export default LoginView;
